import styles from '@/pages/VideoMeeting/chat.less';
import { EnterOutlined } from '@ant-design/icons';
import { Button, Input } from 'antd';
import { useState } from 'react';

const ChatInput = (props: { meetingCode: string }) => {
  const { meetingCode } = props;
  const { TextArea } = Input;
  const [chatMessageInput, setChatMessageInput] = useState<string>('');
  const userInfo = JSON.parse(localStorage.getItem('userInfo')!);
  const handleKeyDown = (event: any) => {
    if (event.key === 'Enter' && event.ctrlKey) {
      // 用户按下了 Ctrl + Enter，执行换行操作
      setChatMessageInput(chatMessageInput + '\n');
      event.preventDefault(); // 阻止默认的 Enter 换行行为
    } else if (event.key === 'Enter') {
      event.preventDefault(); // 阻止默认的 Enter 换行行为
      setChatMessageInput('');
      //告知服务器发送聊天信息
      const message = {
        messageType: 'chatInput',
        userId: userInfo.id,
        userName: userInfo.userName,
        chatMessage: chatMessageInput,
        meetingCode: meetingCode,
      };
      sendMessage(message);
    }
  };

  const sendMessage = async (message: {}) => {
    window.tm!.ipcRenderer.send(
      'send-websocket-message',
      JSON.stringify(message),
    );
  };
  return (
    <div className={styles.chatDown}>
      <TextArea
        value={chatMessageInput}
        rows={6}
        placeholder="请输入消息"
        maxLength={200}
        onKeyDown={(e) => {
          handleKeyDown(e);
        }}
        onChange={(v) => {
          setChatMessageInput(v.target.value);
        }}
      />
      <div className={styles.sendButton}>
        <span className={styles.tips}>
          按{<EnterOutlined />}发送/Ctrl+{<EnterOutlined />}换行
        </span>
        <Button
          disabled={chatMessageInput?.length == 0}
          onClick={() => {
            setChatMessageInput('');
            //告知服务器发送聊天信息
            const message = {
              messageType: 'chatInput',
              userId: userInfo.id,
              userName: userInfo.userName,
              chatMessage: chatMessageInput,
              meetingCode: meetingCode,
            };
            sendMessage(message);
          }}
        >
          发送
        </Button>
      </div>
    </div>
  );
};

export default ChatInput;
